package com.qny.ai.service.impl;

import com.qny.ai.util.AvatarGenerator;
import com.qny.ai.service.impl.KodoStorageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class AvatarUploadService {

    private final AvatarGenerator avatarGenerator;
    private final KodoStorageService kodoStorageService;
    
    // 缓存已生成的头像URL
    private final Map<String, String> avatarCache = new HashMap<>();
    
    /**
     * 为角色生成并上传头像
     * @param roleName 角色名称
     * @param category 角色类别
     * @return 头像URL
     */
    public String generateAndUploadAvatar(String roleName, String category) {
        String cacheKey = roleName + "_" + category;
        
        // 检查缓存
        if (avatarCache.containsKey(cacheKey)) {
            return avatarCache.get(cacheKey);
        }
        
        try {
            // 生成头像
            String base64Avatar = avatarGenerator.generateAvatar(roleName, category);
            if (base64Avatar == null) {
                log.error("生成头像失败: {}", roleName);
                return null;
            }
            
            // 解码Base64
            byte[] imageBytes = Base64.getDecoder().decode(base64Avatar);
            
            // 生成文件名
            String fileName = "avatars/system/" + category + "/" + roleName + ".png";
            
            // 上传到Kodo
            String avatarUrl = kodoStorageService.uploadBytes(imageBytes, "png");
            
            if (avatarUrl != null) {
                // 缓存URL
                avatarCache.put(cacheKey, avatarUrl);
                log.info("头像上传成功: {} -> {}", roleName, avatarUrl);
            } else {
                log.error("头像上传失败: {}", roleName);
            }
            
            return avatarUrl;
            
        } catch (Exception e) {
            log.error("生成并上传头像失败: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 批量生成系统角色头像
     */
    public void generateSystemRoleAvatars() {
        log.info("开始生成系统角色头像...");
        
        // 助手类角色
        String[] assistantRoles = {
            "智能助手", "编程助手", "学习助手", "翻译助手", "写作助手",
            "数据分析师", "健康顾问", "理财顾问", "法律顾问", "心理咨询师"
        };
        
        // 娱乐类角色
        String[] entertainmentRoles = {
            "搞笑达人", "游戏伙伴", "音乐DJ", "电影评论家", "段子手",
            "聊天达人", "故事讲述者", "模仿达人", "魔术师", "喜剧演员"
        };
        
        // 教育类角色
        String[] educationRoles = {
            "数学老师", "英语老师", "历史老师", "物理老师", "化学老师",
            "生物老师", "地理老师", "语文老师", "艺术老师", "体育老师"
        };
        
        // 商务类角色
        String[] businessRoles = {
            "商业顾问", "市场营销专家", "项目管理专家", "人力资源专家", "财务分析师",
            "销售专家", "运营专家", "产品经理", "客户服务专家", "创业导师"
        };
        
        // 创作类角色
        String[] creativeRoles = {
            "创意设计师", "文案策划", "摄影师", "插画师", "音乐制作人",
            "视频制作人", "游戏设计师", "动画师", "建筑师", "时尚设计师"
        };
        
        // 生活类角色
        String[] lifeRoles = {
            "生活顾问", "美食达人", "旅行专家", "健身教练", "园艺师",
            "宠物专家", "家居设计师", "育儿专家", "情感顾问", "时间管理专家"
        };
        
        // 生成头像
        generateAvatarsForCategory(assistantRoles, "assistant");
        generateAvatarsForCategory(entertainmentRoles, "entertainment");
        generateAvatarsForCategory(educationRoles, "education");
        generateAvatarsForCategory(businessRoles, "business");
        generateAvatarsForCategory(creativeRoles, "creative");
        generateAvatarsForCategory(lifeRoles, "life");
        
        log.info("系统角色头像生成完成");
    }
    
    private void generateAvatarsForCategory(String[] roles, String category) {
        for (String roleName : roles) {
            String avatarUrl = generateAndUploadAvatar(roleName, category);
            if (avatarUrl != null) {
                log.info("生成头像成功: {} ({}) -> {}", roleName, category, avatarUrl);
            } else {
                log.error("生成头像失败: {} ({})", roleName, category);
            }
        }
    }
    
    /**
     * 获取头像URL（从缓存）
     */
    public String getAvatarUrl(String roleName, String category) {
        String cacheKey = roleName + "_" + category;
        return avatarCache.get(cacheKey);
    }
    
    /**
     * 清空缓存
     */
    public void clearCache() {
        avatarCache.clear();
        log.info("头像缓存已清空");
    }
}
